<?php
if (!defined('ABSPATH')) {
	define('ABSPATH', dirname(dirname(__FILE__)) . '/');
}

require_once ABSPATH . 'dr-config.php';
require_once ABSPATH . DRINC . '/dr-base.php';
require_once ABSPATH . DRINC . '/dr-functions.php';

require_once ABSPATH . DRINC . '/dr-themes.php';
require_once ABSPATH . DRINC . '/mygravatar.php';

require_once ABSPATH . DRINC . '/dr-smarty.php';

require_once ABSPATH . DRINC . '/dr-page-check-login.php';

# 确保开启session
if (!isset($_SESSION)) {
	session_start();
}

if (isset($_GET['type']) && isset($_GET['qid'])) {
	$_SESSION['type'] = dr_get('type');
	$_SESSION['qid'] = dr_get('qid');
	$_SESSION['aid'] = dr_get('aid');
	$_SESSION['location'] = dr_get('location');
}


if (dr_post("submit") == true) {

	$sys_captcha = $_SESSION['captcha'];

	$username = dr_post('username');
	$email = dr_post('email');
	$password = dr_post('password');
	$repassword = dr_post('repassword');
	$user_captcha = dr_post('captcha');

	if (dr_is_username_exist($username)) {
		dr_fatal_error("The username '$username' already exist...");
	} elseif (dr_is_email_valid($email) == 1) {
		dr_fatal_error("The email format is not right...");
	} elseif (dr_is_email_valid($email) == 2) {
		dr_fatal_error("The email '$email' already exist...");
	} else { # 当用户名和邮箱正确时注册、登陆并跳转
		$posts = array(
			'action' => 'register',
			'username' => $username,
			'password' => $password,
			'email' => $email
		);

		$data = json_decode(dr_server_request('dr-app-users.php', $posts), true);

		$user_id = $data['userid'];

		$_SESSION['user_id'] = $user_id;

		$redirect = BASE_HOSTPATH . 'index.php';

		if (isset($_SESSION['type']) && isset($_SESSION['qid'])) {
			$question_id = $_SESSION['qid'];
			$answer_id = $_SESSION['aid'];
			$type = $_SESSION['type'];
			$location = $_SESSION['location'];
			switch ($type)
			{
				case 'show_question_vote':
				case 'comment':
					$redirect = BASE_HOSTPATH . "dr-includes/dr-page-question-answer.php?qid=$question_id#$location";
					break;

				case 'questions_vote':
					$redirect = BASE_HOSTPATH . "dr-includes/dr-page-question-list.php#$location";
			}
			unset($_SESSION['type']);
			unset($_SESSION['qid']);
			unset($_SESSION['aid']);
			unset($_SESSION['location']);
		}
		dr_set_logged_in_user($user_id, $username);
		$smarty->assign('is_login', $user_id);

		header("Location: $redirect");
		die;
	}
}

$smarty->assign('page_title', 'Register - iDaren');
$smarty->assign('captcha_img', 'dr-includes/dr-captcha.php');

$content = array();
$content['top_navs'] = get_page_top_navigation();
$content['menus'] = get_page_menus('');
$content['tabs'] = get_page_tabs('register', '');

$smarty->assign('content', $content);

# 显示注册页面
$smarty->display('register.tpl');
